import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qilo/core/constants/app_icons.dart';

class EventInquiryPage extends StatefulWidget {
  final String eventType; // 'september' or 'october'

  const EventInquiryPage({super.key, required this.eventType});

  @override
  State<EventInquiryPage> createState() => _EventInquiryPageState();
}

class _EventInquiryPageState extends State<EventInquiryPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  List<ChatMessage> _messages = [];

  @override
  void initState() {
    super.initState();
    _initializeDefaultMessages();
  }

  void _initializeDefaultMessages() {
    // 延迟添加消息以模拟真实聊天体验
    Future.delayed(const Duration(milliseconds: 500), () {
      _addBotMessage(_getWelcomeMessage());
    });

    Future.delayed(const Duration(milliseconds: 1500), () {
      _addBotMessage(_getEventDetailsMessage());
    });

    Future.delayed(const Duration(milliseconds: 2500), () {
      _addBotMessage(_getRegistrationMessage());
    });
  }

  String _getWelcomeMessage() {
    if (widget.eventType == 'september') {
      return "🎵 Welcome to our Team Collaboration Performance Competition! I'm here to help you with registration and answer any questions about the September event.";
    } else {
      return "🎸 Welcome to The Ultimate Guitar Showdown! I'm here to assist you with registration and provide details about our October competition.";
    }
  }

  String _getEventDetailsMessage() {
    if (widget.eventType == 'september') {
      return "📅 Our September event focuses on team collaboration! Teams of 2-5 members will perform together. You can choose from our pre-assigned songs or submit your original composition. What interests you most?";
    } else {
      return "🎼 Our October competition is all about original compositions! Contestants perform solo or with backing bands. You'll have up to 5 minutes to showcase your creativity. Are you ready to share your musical story?";
    }
  }

  String _getRegistrationMessage() {
    if (widget.eventType == 'september') {
      return "✨ To register your team, I'll need: team member details, preferred instruments, and your song choice. We also provide rehearsal time and equipment. Would you like to start the registration process?";
    } else {
      return "🌟 For registration, please prepare: your original composition details, sheet music or demo recording, and performance preferences. Ready to sign up for this amazing showcase?";
    }
  }

  void _addBotMessage(String text) {
    if (mounted) {
      setState(() {
        _messages.add(
          ChatMessage(text: text, isUser: false, timestamp: DateTime.now()),
        );
      });
      _scrollToBottom();
    }
  }

  void _addUserMessage(String text) {
    setState(() {
      _messages.add(
        ChatMessage(text: text, isUser: true, timestamp: DateTime.now()),
      );
    });
    _scrollToBottom();

    Future.delayed(const Duration(milliseconds: 1000), () {
      _addBotMessage(
        "Thank you for your message! Our team will get back to you shortly with more details about the registration process.",
      );
    });
  }

  void _scrollToBottom() {
    Future.delayed(const Duration(milliseconds: 100), () {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _sendMessage() {
    if (_messageController.text.trim().isNotEmpty) {
      _addUserMessage(_messageController.text.trim());
      _messageController.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildAppBar(),
              Expanded(child: _buildChatAreaWithBackground()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.w),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: Center(
              child: Text(
                'Event Inquiry',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                ),
              ),
            ),
          ),
          Icon(MyIcons.iconReport, color: Colors.white, size: 24.w),
        ],
      ),
    );
  }

  Widget _buildChatAreaWithBackground() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/activity-bg.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        children: [
          _buildOnlineStatus(),
          Expanded(child: _buildMessagesList()),
          _buildMessageInput(),
        ],
      ),
    );
  }

  Widget _buildOnlineStatus() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
      decoration: BoxDecoration(
        color: const Color(0xFFCD8B76),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Text(
        'Online: 12',
        style: TextStyle(
          fontSize: 14.sp,
          color: Colors.white,
          fontFamily: 'Poppins',
        ),
      ),
    );
  }

  Widget _buildMessagesList() {
    return ListView.builder(
      controller: _scrollController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: _messages.length,
      itemBuilder: (context, index) {
        return _buildMessageBubble(_messages[index]);
      },
    );
  }

  Widget _buildMessageBubble(ChatMessage message) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!message.isUser) ...[
            CircleAvatar(
              radius: 20.r,
              backgroundImage: const AssetImage('assets/images/bot_avatar.png'),
              backgroundColor: Colors.grey[300],
            ),
            SizedBox(width: 12.w),
          ],
          Flexible(
            child: Container(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width * 0.7,
              ),
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color:
                    message.isUser
                        ? const Color(0xFFCD8B76)
                        : const Color(0xFFD4A574).withValues(alpha: 0.8),
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Text(
                message.text,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                  fontFamily: 'Poppins',
                  height: 1.4,
                ),
              ),
            ),
          ),
          if (message.isUser) ...[
            SizedBox(width: 12.w),
            CircleAvatar(
              radius: 20.r,
              backgroundImage: const AssetImage(
                'assets/images/user_avatar.png',
              ),
              backgroundColor: Colors.grey[300],
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildMessageInput() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24.r,
            backgroundImage: const AssetImage('assets/images/user_avatar.png'),
            backgroundColor: Colors.grey[300],
          ),

          SizedBox(width: 12.w),

          // 输入框容器
          Expanded(
            child: Container(
              height: 60.h,
              decoration: BoxDecoration(
                color: const Color(0xFFD4A574).withValues(alpha: 0.8),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Row(
                children: [
                  // 输入框区域
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      child: TextField(
                        controller: _messageController,
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                          fontFamily: 'Poppins',
                        ),
                        decoration: InputDecoration(
                          hintText: 'Say Something',
                          hintStyle: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white.withValues(alpha: 0.7),
                            fontFamily: 'Poppins',
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.zero,
                        ),
                        onSubmitted: (_) => _sendMessage(),
                      ),
                    ),
                  ),

                  // 右侧发送按钮
                  Padding(
                    padding: EdgeInsets.all(6.w),
                    child: GestureDetector(
                      onTap: _sendMessage,
                      child: Container(
                        width: 48.w,
                        height: 48.w,
                        decoration: const BoxDecoration(
                          color: Color(0xFFCD8B76),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          MyIcons.iconSend,
                          color: Colors.white,
                          size: 18.w,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }
}

class ChatMessage {
  final String text;
  final bool isUser;
  final DateTime timestamp;

  ChatMessage({
    required this.text,
    required this.isUser,
    required this.timestamp,
  });
}
